package 查找热点数据.main;

import java.util.*;

public class Main {
    public static String solution(int[] nums, int k) {
        // Please write your code here
        Map<Integer, Integer> frequencyMap = new HashMap<>();
        for (int num : nums) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }

        // 使用最小堆来维护出现频率前 k 高的元素
        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(
                (a, b) -> a.getValue() - b.getValue()
        );

        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }

        // 从堆中取出元素，得到最终结果
        int[] result = new int[k];
        for (int i = k - 1; i >= 0; i--) {
            result[i] = minHeap.poll().getKey();
        }

        return (toStringHaven(result)).substring(1, (toStringHaven(result).length() - 1));
    }


//    from Array.toString()
    public static String toStringHaven(int[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('"');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append('"').toString();
            b.append(",");
        }
    }
    public static void main(String[] args) {
        //  You can add more test cases here
        int[] nums1 = {1, 1, 1, 2, 2, 3};
        int[] nums2 = {1};


        System.out.println(solution(nums1, 2).equals("1,2"));
        System.out.println(solution(nums2, 1).equals("1"));
    }
}